<template>
  <PageWrapper>
<!--    <div class="lg:flex">-->
<!--      <div class="lg:w-2/10 w-full !mr-4 enter-y">-->
    <div :class="{ 'textSelect': textDisable}" :style="winWidth">
      <div style="display: inline-block;vertical-align: top;" :style = "leftClass">
        <Card class="!my-4 enter-y" :style="cardHeight" style="overflow-y: scroll">
          <ElTree ref="parentRef" :data="treeData" :props="defaultProps"  node-key="childNodeCode" :default-expanded-keys="expandNodes" @node-click="handleNodeClick" />
          <Loading :loading="treeLoading" absolute="true" :tip="loadingText"/>
        </Card>
      </div>
<!--      <div class="lg:w-8/10 w-full enter-y">-->
      <div class="draggable" style="width: 5px; display: inline-block;vertical-align: top;" :style="cardHeight"></div>
      <div style="display: inline-block;vertical-align: top;" :style = "rightClass">
        <Card class="!my-4 enter-y common_style"  :style="cardHeight">
          <el-tabs v-model="activeName" class="common_style" type="border-card" @tab-click="handleClick">

          <el-tab-pane :style="tabHeight" label="规格参数" name="1">
              <!--     进度条         -->
              <div class="container" style="margin-left: 10px;margin-bottom: 10px">
                <div style="display:flex;" v-for="(item,key) in progressList">
                  <div class="box" :class="{ 'red-background': activeDiv === item }">
                    {{item}}
<!--                    <div :class="{ 'red-background': activeDiv === item }">{{item}}</div>-->
                  </div>
                  <div v-if="key !== progressList.length -1" class="arrow-with-line">
                    <div class="line" :class="{ 'line-is-active': activeDiv === item }"></div>
                    <div class="arrow" :class="{ 'arrow-is-active': activeDiv === item }"></div>
                  </div>
                </div>
<!--                <div class="box">-->
<!--                  <div :class="{ 'red-background': activeDiv === 'chart开发' }">chart开发</div>-->
<!--                </div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box"><div :class="{ 'red-background': activeDiv === '开发' }">开发</div></div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box">导入</div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box">成本</div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box">成熟</div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box">退市中</div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box">已退市</div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box">冻结</div>-->
<!--                <div class="arrow-with-line">-->
<!--                  <div class="line"></div>-->
<!--                  <div class="arrow"></div>-->
<!--                </div>-->
<!--                <div class="box">废弃</div>-->
              </div>
              <el-scrollbar :max-height="scrollMaxHeight1">
              <el-descriptions class="margin-top" border :column="1" v-for="item in basicInfo" :title=item.title>
                <el-descriptions-item width="100" label-class-name="table-content-header" class-name="table-content-header"  label = "属性描述">内容</el-descriptions-item>
                <el-descriptions-item width="100" label-class-name="table-content-body" class-name="table-content-body" v-for="chItem in item.childs " :key="chItem.id" :label = chItem.label>{{chItem.value}}</el-descriptions-item>
              </el-descriptions>
              </el-scrollbar>
            </el-tab-pane>
<!--            <el-tab-pane  :style="tabHeight"  label="规格参数" name="2">-->
<!--              <el-scrollbar :max-height="scrollMaxHeight2">-->
<!--                <el-descriptions  class="margin-top" border :column="1" v-for="item in extraInfo" :title=item.title>-->
<!--                  <el-descriptions-item width="100" v-for="chItem in item.childs " :key="chItem.id" :label = chItem.label>{{chItem.value}}</el-descriptions-item>-->
<!--                </el-descriptions>-->
<!--              </el-scrollbar>-->
<!--            </el-tab-pane>-->
            <el-tab-pane label="相关型号"  name="3">
              <OfferingProductList  ref="product"/>
            </el-tab-pane>
            <el-tab-pane label="产品文档"  name="4">
              <OfferingDocumentList ref="doc"/>
            </el-tab-pane>
          </el-tabs>
        </Card>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
import {computed, nextTick, onMounted, reactive, ref, watch, watchEffect} from 'vue';
import {Card} from 'ant-design-vue';
import {PageWrapper} from '/@/components/Page';
import OfferingProductList from "@/views/PBI/product/component/offeringProductList.vue";
import OfferingDocumentList from "@/views/PBI/product/component/OfferingDocumentList.vue";
import type {TabsPaneContext} from 'element-plus'
import * as API from '@/api/pbi/offering';
import { Loading } from '/@/components/Loading';

import {VxeGridProps, VxeTablePropTypes} from 'vxe-table'
import {useGlobSetting} from "@/hooks/setting";
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

const treeLoading = ref(false);
const loadingText = ref('数据正在加载中...');
const expandNodes = ref([]);

const apiParam = ref('ss'); // 示例接口参数
  const activeDiv = ref('');

const product= ref()
const doc= ref()
  //监控
  watch(apiParam, (newValue) => {
    activeDiv.value = newValue;
  });
  //挂载完成
  onMounted(()=> {

  })

  const items = [
    {
      'id': 1,
      'title': "22",
      "childs":[
        {
          'name': 'test1',
          'label': 'we',
          'id': 3
        },
        {
          'name': 'test2',
          'label': 'we2',
          'id': 4
        },
      ]
    },
    {
      'id': 22,
      'title': "23",
      "childs":[
        {
          'name': 'test1',
          'label': 'we',
          'id': 5
        },
        {
          'name': 'test2',
          'label': 'we2',
          'id': 6
        },
      ]
    },

  ];
  const attributeParams = ref([]);
  interface info {
    id: string;
    title: string
    childs: any[];
  }
  const basicInfo = ref<info[]>([]);
  const extraInfo = ref<info[]>([]);
  const testItems = [
    {
      "基本信息": [
        {
          "internalName":"offeringName", "displayName":"Offering名称","value":"DA180系列380V1.5～2kW"
        },
        {
          "internalName":"productSeries", "displayName":"产品系列名","value":"AX系列"
        },
        {
          "internalName":"offeringNumber", "displayName":"Offering编码","value":"PBI-0000000007"
        }
      ]
    },
    {
      "控制性能": [
        {
          "internalName":"programPlatform", "displayName":"编程平台","value":"Invtmatic Studio"
        }
      ]
    },
    {
      "外围接口": [
        {
          "internalName":"USBInterface", "displayName":"USB接口","value":"是"
        },
        {
          "internalName":"SDCard", "displayName":"SD卡","value":"是"
        },
        {
          "internalName":"offeringNumber", "displayName":"Offering编码","value":"PBI-0000000007"
        }
      ]
    },
    {
      "辅助说明": [
        {
          "internalName":"installType", "displayName":"安装方式","value":"导轨"
        }
      ]
    }
  ]

const  baseInfoMap = ref({
  '基本信息': 1,
  '基础属性组': 2,
  '控制性能': 3,
  '外围接口': 4,
  "辅助说明": 5
})


  const convert2EldElDescription = (params: object) => {
    basicInfo.value = [];
    extraInfo.value = [];
    if (params) {
      let item = params;
      let keys = Object.keys(item);
      if (keys.includes('基本信息')) {
        if (item['基本信息'] && item['基本信息'].length >0) {
          let list = item['基本信息'].filter(a=> a.internalName === 'lifecycleState')
          if (list && list.length > 0) {
            activeDiv.value = list[0].value;
          }
        }
      }
      keys.forEach(key=>{
        // if (key === '基础属性组') {
          if (item[key].length > 0) {
            let child = [];
            item[key].forEach(item2 => {
                child.push({
                  id: item2["internalName"],
                  label: item2["displayName"],
                  value: item2["value"]
                })
              }
            );
            if (key === '基本信息') {
              child = child.filter(ch=> ch.label !== 'Offering编码');
            }
            basicInfo.value.push({
              id: baseInfoMap.value[key]?baseInfoMap.value[key] : 30,
              title: key ==='基础属性组' ? '基础属性' : key,
              childs: child
            });
          }
        // } else {
        //   if (item[key].length > 0) {
        //     let child = [];
        //     item[key].forEach(item2 => {
        //         child.push({
        //           id: item2["internalName"],
        //           label: item2["displayName"],
        //           value: item2["value"]
        //         })
        //       }
        //     );
        //     extraInfo.value.push({
        //       id: key,
        //       title: key,
        //       childs: child
        //     });
        //   }
        // }
      })
      //规格参数排序
      basicInfo.value.sort((a, b) => a.id-b.id )
    }


  };
  // convert2EldElDescription(testItems)
  // console.log(basicInfo.value);
  // console.log(extraInfo.value);
  const registerRef = () => {
    debugger
    // apiParam.value = 'chart开发';
    apiParam.value = '开发';
  }

  //vxe-grid
  interface RowVO {
    name: string
    sex: string
  }

  const gridOptions = reactive<VxeGridProps<RowVO>>({
    border: true,
    loading: false,
    height: 300,
    columns: [],
    data: [],
    columnConfig: {
      resizable: true
    }
  })

  const activeName = ref<String>('1');

  // 通用行合并函数（将相同多列数据合并为一行）
  const mergeRowMethod: VxeTablePropTypes.SpanMethod<RowVO> = ({ row, _rowIndex, column, visibleData }) => {
    const fields = ['name']
    const cellValue = row[column.field]
    if (cellValue && fields.includes(column.field)) {
      const prevRow = visibleData[_rowIndex - 1]
      let nextRow = visibleData[_rowIndex + 1]
      if (prevRow && prevRow[column.field] === cellValue) {
        return { rowspan: 0, colspan: 0 }
      } else {
        let countRowspan = 1
        while (nextRow && nextRow[column.field] === cellValue) {
          nextRow = visibleData[++countRowspan + _rowIndex]
        }
        if (countRowspan > 1) {
          return { rowspan: countRowspan, colspan: 1 }
        }
      }
    }
  }

  // 递归函数
  const dg = function(list, res) {
    list.forEach(item=> {
      const itemCh = res.filter(a => a.childNodeCode != '' && a.childNodeCode != null && a.parentNodeCode == item.childNodeCode)
      if (itemCh && itemCh.length >0) {
        itemCh.sort((a,b) => a.childNodeName.localeCompare(b.childNodeName))
        item.children = itemCh;
        // 再次调用dg这个函数 再走一遍
        dg(item.children, res);
      }
    })
  }

  const initTree = async () => {
    treeLoading.value = true
    try {
      const {productRootId} = useGlobSetting();
      const {data} = await API.getProductCatelogTree({productCatelogNumber: productRootId});
      if (data) {
        // console.log(data);
        let list = JSON.parse(data);
        const level1List = list.filter(a => a.level == 1)
        if (level1List && level1List.length > 0) {
          level1List.sort((a,b) => a.childNodeName.localeCompare(b.childNodeName))
          dg(level1List, list);
          //构造根对象
          const rootNode = {
            "parentNodeCode": "",
            "parentNodeName": "",
            "parentNodeType": "",
            "childNodeCode": level1List[0].parentNodeCode,
            "childNodeName": level1List[0].parentNodeName,
            "level": 0,
            "children": level1List
          }
          // console.log(rootNode)
          treeData.value.push(rootNode)
          expandNodes.value.push(rootNode.childNodeCode)
          level1List.forEach(item=> {
            expandNodes.value.push(item.childNodeCode)
            if (item.children && item.children.length > 0) {
              item.children.forEach(subItem=> {
                expandNodes.value.push(subItem.childNodeCode)
              })
            }
          })
        }
        await nextTick(() => {
          addWatch();
        })
        // console.log('dwfw7777777777777777777')
        // console.log(treeData.value)
      }
    } finally {
      treeLoading.value = false
    }

  }

  const initOfferingInfo = async () => {
    console.log('111')
    console.log(route.query)
    console.log('222')
    if (route.query.pbinumber) {
      activeName.value = '1'
      let res = await API.getOfferingInfo({pbinumber: route.query.pbinumber})
      if (res && res.success === 'true') {
        let result = JSON.parse(res.data)
        convert2EldElDescription(result)
      }
      route.query = {}
    }
  }

  initTree();
// 加载offering规格参数
  initOfferingInfo();

  interface Tree {
    parentNodeCode: string;
    parentNodeName: string;
    parentNodeType: string;
    childNodeCode: string;
    childNodeName: string;
    level: number;
    children?: Tree[];
  }

  const nodeCode = ref<String>();

  const handleNodeClick = async (data: Tree) => {
    // 清除之前的数据
    basicInfo.value = [];
    activeDiv.value = '';
    product.value.tableData = [];
    doc.value.tableData = [];
    activeName.value = '1'
    if (data.children == null || data.children.length == 0) {
      nodeCode.value = data.childNodeCode;
      //调用第一个子组件的方法
      let res = await API.getOfferingInfo({pbinumber: nodeCode.value})
      if (res && res.success === 'true') {
        let result = JSON.parse(res.data)
        convert2EldElDescription(result)
      }
    }
    // nextTick(()=>{
    //   addWatch();
    // })
    // console.log(data);
  };
  const winWidth = computed(() => {
    let winWidth = window.innerWidth-30;
    let winHeight = window.innerHeight - 70;
    return {
      width: winWidth + 'px',
      height: winHeight + 'px',
    };
  });
  const cardHeight = computed(() => {
    let winHeight = window.innerHeight - 70;
    return {
      height: winHeight + 'px',
    };
  });
  const tabHeight = computed(() => {
    let winHeight = window.innerHeight - 220;
    return {
      height: winHeight + 'px',
    };
  });
  const scrollMaxHeight1 = computed(() => {
    let size = window.innerHeight - 250;
    return size;
  });
  const scrollMaxHeight2 = computed(() => {
    let size = window.innerHeight - 200;
    return size;
  });

  const data: Tree[] = [];
  const treeData  = ref<Tree[]>([]);

  const defaultProps = {
    children: 'children',
    label: 'childNodeName',
  };
  const handleClick = (tab: TabsPaneContext, event: Event) => {
    // console.log(tab.paneName)
    switch (tab.paneName) {
      case "1":
        break;
      // case "2":
      //   break;
      case "3":
        product.value.findTableData(nodeCode.value);
        break;
      case "4":
        doc.value.findTableData(nodeCode.value);
        break;
      default:
        break;
    }
  }
  const progressList = ref(['Charter开发','开发','导入','成长','成熟','退市中','已退市','冻结','废弃']);

const textDisable = ref<boolean>(false)
const leftWidth = ref<number>((window.innerWidth - 30) * 0.15)
const rightWidth = ref<number>()
const leftClass = computed(() => {
  return {
    width: leftWidth.value + 'px',
  };
});
const rightClass = computed(() => {
  let winWidth = window.innerWidth-30 -leftWidth.value-5;
  return {
    width: winWidth + 'px',
  };
});
// const computeWidth = () => {
//   let treeEle = document.querySelector(".el-tree .tree-node")
//   console.log(treeEle.clientWidth)
// }
const parentRef = ref(null);
const addWatch = ()=>{
  let elTree = parentRef.value.$el
  if (elTree != null) {
    let elNode = elTree.firstElementChild;
    if (elNode != null && elNode.className === 'el-tree-node is-expanded is-focusable') {
      // debugger
      let val = parentRef.value.$el.firstElementChild.clientWidth
      leftWidth.value =  val + 60 - 3;
      // debugger
      console.log("宽度已变化");
      // watch(()=>{
      //   return parentRef.value.$el.firstElementChild.clientWidth;
      // },(value)=>{
      //   console.log("宽度已变化2");
      //   debugger
      //   leftWidth.value = (value + 60);
      //   console.log(leftWidth.value);
      // },{immediate: true})
      // watchEffect(() => {
      //   // 获取子元素的宽度
      //   if (parentRef.value.$el.firstElementChild) {
      //     console.log(parentRef.value.$el.firstElementChild)
          // debugger
          // console.log(parentRef.value.el$)
          // const childWidth = parentRef.value.clientWidth;
          // leftWidth.value = parentRef.value.$el.firstElementChild.clientWidth;
          // console.log('子元素的宽度：', childWidth);
      //   }
      // });
    }
  }

}
// watchEffect(() => {
//   if (parentRef.value) {
//     // debugger
//     // 获取子元素的宽度
//     let elTree = parentRef.value.$el
//     if (elTree != null) {
//       let elNode = elTree.firstElementChild;
//       if (elNode != null && elNode.className === 'el-tree-node is-expanded is-focusable') {
//           // console.log("宽度已变化")
//       }
//
//     }
//     // console.log(parentRef.value.el$)
//     const childWidth = parentRef.value.clientWidth;
//     // console.log('子元素的宽度：', childWidth);
//   }
// });
//
// watch(()=> {
//   if (parentRef.value != null) {
//     let test = document.querySelector(".el-tree .tree-node");
//     // console.log(parentRef.value.children)
//     // console.log(parentRef)
//     // debugger
//     // console.log(parentRef.value.clientWidth);
//     // console.log(parentRef);
//     if (test !== null) {
//       return test.clientWidth;
//     }
//   } else {
//
//   }
//   return leftWidth.value;
// },(value)=>{
//   leftWidth.value = value;
// },{immediate : true})
nextTick(()=> {
  let draggable = document.querySelector('.draggable');
  draggable.onmousedown = function (e) {
    let startX = e.clientX;
    let startLeft = leftWidth.value;
    textDisable.value = true
    document.onmousemove = function (e) {
      // 在这里处理拖动事件
      let offset = e.clientX - startX
      if (startLeft + offset > (window.innerWidth - 30) * 0.3) {
        leftWidth.value = (window.innerWidth - 30) * 0.3
      } else if (startLeft + offset < (window.innerWidth - 30) * 0.15) {
        leftWidth.value = (window.innerWidth - 30) * 0.15
      } else {
        leftWidth.value = startLeft + offset;
      }
    }
    document.onmouseup = function (ev) {
      ev.stopPropagation()
      document.onmousemove = null;
      document.onmouseup = null
      textDisable.value = false
    };
  };
})
</script>

<style scoped>
  .tabHeight {
    height: 100%;
  }

  .red-background {
    background: #6096e6!important;
  }
  .container {
    display: flex;
    align-content: center;
  }

  .box {
    /*flex: 4; !* 等分宽度 *!*/
    padding: 5px 10px;
    border: 1px solid #000000;
    border-radius: 5px;
    align-content: center;
    background: #a6a6a6;
    color: #ffffff;
    white-space: nowrap;
  }

  /*.box:last-child {*/
  /*  margin-right: 0; !* 可选，去除最后一个box的间距 *!*/
  /*}*/
  .arrow-with-line {
    display: flex;
    align-items: center;
    margin-left: 10px;
  }
  :deep(.table-content-header) {
    background: #6096e6!important;
    color: #ffffff!important;
    text-align: center!important;
    font-weight: bold!important;
    font-size: 16px!important;
  }

  :deep(.table-content-body) {
    border-color: #ffffff !important;
    background-color: #d2ddf5 !important;
    color: black;
  }

  .arrow-is-active{
    border-left: 5px solid #6096e6!important;
  }

  .line-is-active{
    background-color: #6096e6!important;
  }

  .arrow {
    width: 0;
    height: 0;
    border-top: 5px solid transparent;  /* 控制箭头的高度 */
    border-bottom: 5px solid transparent;  /* 控制箭头的高度 */
    border-left: 5px solid #a6a6a5;  /* 控制箭头的颜色和宽度 */
  }

  .line {
    width: 30px; /* 控制横线的长度 */
    height: 2px;
    background-color: #a6a6a5; /* 控制横线的颜色 */
    margin-left: -10px; /* 控制横线与箭头之间的间距，通过负值实现重叠 */
  }
  :deep(.vxe-grid .vxe-table--header-wrapper) {
  display: none;
  }
  :deep(.el-descriptions__header) {
    margin-top: 4px !important;
    margin-bottom: 4px !important;
  }
  :deep( .el-descriptions__header .el-descriptions__title) {
    font-size: 12px !important;
  }
  :deep( .el-descriptions__body) {
    border:1px solid #c8cbcf !important;
    padding: 3px 3px;
  }
  :deep( .el-descriptions__body .el-descriptions__label) {
    font-weight: 400;
    width: 20% !important;
  }
  :deep( .el-descriptions__body .el-descriptions__content) {
    width: 80% !important;
  }

  :deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item) {
    transition: all var(--el-transition-duration) var(--el-transition-function-ease-in-out-bezier);
    border: 2px solid #ffffff;
    margin-bottom: 3px;
    color: #ffffff;
    background: #a6a6a6;
    font-weight: bold;
  }

  :deep(.el-tabs--border-card>.el-tabs__header) {
    background-color: #daecf8;
    border-bottom: 1px solid var(--el-border-color-light);
    margin: 0;
  }

  :deep(.el-tabs__nav) {
    background: #ffffff;
    display: flex;
    white-space: nowrap;
    position: relative;
    transition: transform var(--el-transition-duration);
    float: left;
    z-index: calc(var(--el-index-normal) + 1);
  }

  :deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active ) {
    color: #ffffff;
    background-color: #5f97e6;
  }

  :deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item:not(.is-disabled):hover) {
     color: #ffffff;
  }

  .common_style{
    background-color: #daecf8;
  }

  :deep(.el-tree>.el-tree-node) {
    min-width:100%;
    display: inline-block;
  }

  .draggable {
    margin-top: 18px;
    width: 5px; /* 设置竖线的宽度 */
    /*height: 100%; !* 设置竖线的高度 *!*/
    background-color: #ffffff; /* 设置竖线的颜色 */
    /*position: absolute;*/
    /*top: 0;*/
    /*left: 50%; !* 设置竖线在页面中的位置 *!*/
    /*transform: translateX(-50%); !* 将竖线居中对齐 *!*/
    z-index: 999; /* 确保竖线位于其他元素之上 */
    /*cursor: ew-resize;*/
    /*resize: horizontal;*/
    cursor: col-resize;
  }
  .draggable:hover{
    /* 设置光标样式为左右调整大小 */
    /*cursor: ew-resize;*/
    background-color: #595454;
  }
  .draggable:active{
    /* 设置光标样式为左右调整大小 */
    /*cursor: ew-resize;*/
    background-color: #595454;
  }
  /* 禁用文本选择 */
  .textSelect {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
</style>
